# -*- coding: UTF-8 -*-


__all__ = ['dump', 'dumps', 'load', 'loads']
__author__ = 'lazyboy <lazyboy.fan@gmail.com>'
__version__ = '1.0.0'

import htmlentitydefs
import re
from core import Lazy
_xml = Lazy()


html_entity_pattern = re.compile("&(\w+?);")
def html_entity_decode_char(m, defs=htmlentitydefs.entitydefs):
    try:
        return defs[m.group(1)]
    except KeyError:
        return m.group(0)

def html_entity_decode(s):
    return html_entity_pattern.sub(html_entity_decode_char, s)

def strip_whitespace(s,strict=False):
    s = s.replace('\r','').replace('\n','').replace('\t','')
    return s.replace(' ','') if strict else s

def file_get_contents(file) :
    fp = open(file,'rb')
    content = fp.read()
    fp.close()
    return content

def file_put_contents(file,s,append=False) :
    fp = open(file,'ab' if append else 'wb')
    fp.write(s)
    fp.close()
    return True

def loads(content,strip_root=True,**kw) :
    if ('unescape' in kw) and kw['unescape']:
        content = html_entity_decode(content)
    return _xml.xml2dict(content,strip_root)

def load(file,strip_root=True,**kw) :
    content = file_get_contents(file)
    if ('unescape' in kw) and kw['unescape']:
        content = html_entity_decode(content)
    return _xml.xml2dict(content,strip_root)

def dumps(obj,**kw) :
    return _xml.dict2xml(obj,**kw)

def dump(obj,file,**kw) :
    tree = _xml.dict2xml(obj,**kw)
    return file_put_contents(file,tree)
